<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .test {
    background: red;
  }

</style>
<template>
  <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
    <FormItem label="类    型" prop="model">
      <Select v-model="formValidate.model" placeholder="类型">
        <Option @click.native="optionClick(item)" v-for="(item,index) in deviceTypeList" :value="item.model"
                :key="'type'+index">{{item.useType + ' ' + item.model}}
        </Option>
      </Select>
    </FormItem>
    <FormItem label="设备名称" prop="name">
      <Input v-model="formValidate.name" placeholder="设备名称"></Input>
    </FormItem>
    <FormItem label="设备编号" prop="sn">
      <Input v-model="formValidate.sn" placeholder="设备编号"></Input>
    </FormItem>
    <FormItem label="设备空间" prop="deviceSpace">
      <Cascader change-on-select :render-format="cascaderFormat" trigger="click" :data="deviceSpaceData"
                v-model="formValidate.deviceSpace" @on-visible-change="spaceInputChange">
        <Input v-model="deviceSpaceText" readonly placeholder="请选择设备空间"></Input>
      </Cascader>
    </FormItem>
    <FormItem label="通协地址" prop="commAddr">
      <Input v-model="formValidate.commAddr" placeholder="通协地址"></Input>
    </FormItem>
    <FormItem label="读取间隔" prop="readInterval">
      <Input v-model="formValidate.readInterval" placeholder="读取间隔"></Input>
    </FormItem>
    <FormItem label="排序值" prop="sort">
      <Input v-model="formValidate.sort" placeholder="排序值"></Input>
    </FormItem>
    <FormItem style="margin: 0;float: right;">
      <!--    <Button type="primary" @click="saveDatasToDb('formValidate')">确定</Button>-->
      <Button type="info" ghost @click="formReset()" style="margin-left: 8px;width: 100px;">重置</Button>
    </FormItem>
  </Form>

</template>
<script>
  export default {
    data: function () {
      const num = (rule, value, callback) => {
        let isNum = /^\+?[1-9][0-9]*$/.test(value)
        if (value === '' || value === undefined || !isNum) {
          callback(new Error('请输入数字！'))
        } else {
          callback()
        }
      }
      const deviceSpaceValidator = (rule, value, callback) => {
        let hasData = null
        if (value.length > 0) {
          hasData = true
        } else {
          hasData = false
        }
        if (value === '' || value === undefined || !hasData) {
          callback(new Error('请选择设备所在空间！'))
        } else {
          callback()
        }
      }
      return {
        deviceSpaceData: [],
        iotSpace: {},
        temporaryVariable: '',
        treeData: [],
        treeDataTem: [],
        editOneData: {},
        formValidate: {
          name: '',
          model: '',
          commAddr: '',
          readInterval: 1,
          sort: '',
          deviceSpace: []
        },
        ruleValidate: {
          name: [{required: true, message: '必填项！', trigger: 'blur'}, {
            required: true,
            message: '必填项！',
            trigger: 'change'
          }],
          model: [{required: true, message: '必填项！', trigger: 'blur'}, {
            required: true,
            message: '必填项！',
            trigger: 'change'
          }],
          sn: [
            {
              required: false,
              message: '必须以字母或下划线开头，编号可包含英文、数字、下划线',
              pattern: /^[a-zA-Z | _]([\u4e00-\u9fa5\w]{1,50})$/,
              trigger: 'blur'
            }
          ],
          commAddr: [{required: true, message: '必填项！', trigger: 'blur'}, {
            required: true,
            message: '必填项！',
            trigger: 'change'
          }],
          readInterval: [{validator: num, trigger: 'blur'}, {validator: num, trigger: 'change'}],
          deviceSpace: [{validator: deviceSpaceValidator, trigger: 'blur'}, {
            validator: deviceSpaceValidator,
            trigger: 'change'
          }]
        },
        deviceTypeList: [],
        devTypeObj: {},
        deviceSpaceText: '',
        spaceShowStatus: false,
        updateInit: true
      }
    },
    created: function () {
    },
    mounted: function () {
      this.list()
      this.devTypeList()
    },
    destroyed: function () {
      this.$Message.destroy()
    },
    methods: {
      saveDatasToDb: function (name) {
        let self = this
        self.$refs[name].validate((valid) => {
          if (valid) {
            // this.$Message.success('Success!')
            sessionStorage.manageDeviceInfo = true
            self.submitReady()
          } else {
            self.$Message.error('请查看提示错误!')
          }
        })
      },
      handleReset: function (name) {
        this.$refs[name].resetFields()
      },
      // 重置form
      formReset: function () {
        let self = this
        self.$refs['formValidate'].resetFields()
        self.deviceSpaceText = ''
        self.formValidate = {
          name: '',
          model: '',
          commAddr: '',
          readInterval: 1,
          deviceSpace: [],
          sort: ''
        }
      },
      // 更新formdata
      updateFormdata: function (data) {
        let self = this
        self.editOneData = JSON.parse(JSON.stringify(data))
        if (self.editOneData.id !== undefined) {
          self.formReset()
          self.formValidate = self.editOneData
          // 设备空间初始化
          self.deviceSpaceText = ''
          self.updateInit = false
          self.deviceSpaceText = self.editOneData.temporaryVariable ? self.editOneData.temporaryVariable : ''
          // 验证用
          self.formValidate.deviceSpace = []
          let id = self.editOneData.iotSpace ? self.editOneData.iotSpace.id : ''
          if (id !== '') {
            self.formValidate.deviceSpace.push(self.editOneData.iotSpace.id)
          }
          // 设备类型初始化
          self.formValidate.model = self.formValidate.iotDevType.model
          // 设备类型存储默认值
          self.devTypeObj = self.formValidate.iotDevType
        } else {
          // 初始化
          self.formReset()
        }
      },
      // submitReady 准备
      submitReady: function () {
        let self = this
        self.formValidate.iotDevType = self.devTypeObj
        // console.log(self.formValidate)
        let chirldData = {
          tab: 'oneTab',
          objStr: JSON.stringify(self.formValidate)
        }
        // 向父组件传数据
        self.$emit('showTab', chirldData)
        if (self.editOneData.id) {
          // 触发父组件函数
          self.$emit('updSubmitReady')
        } else {
          self.$emit('saveSubmitReady')
        }
      },
      // 树 数据list
      list: function () {
        let self = this
        let getData = {
          'size': 100000,
          'page': self.pageIndex,
          'searchParam': self.queryStr
        }
        window.myapi.space_list(getData).then(function (res) {
          if (res.data.status === 200) {
            self.treeDataTem = res.data.data.content
            self.treeReady(res.data.data.content)
          } else {
            let msg = res.data.msg ? res.data.msg : '请求数据失败!'
            self.$Message.error({content: msg, duration: 5, closable: true})
          }
        }).catch(function (e) {
          if (e && e.response && e.response.data) {
            let msg = e.response.data.message ? e.response.data.message : '请求数据失败!'
            self.$Message.error({content: msg, duration: 5, closable: true})
          }
        })
      },
      // 级联选择 处理为标准格式
      treeReady: function (arr) {
        let self = this
        self.treeData = []
        let one = self.treeRoot(arr)
        self.treeData.push(one)
        // 级联选择 格式标准化处理
        self.deviceSpaceData = self.deviceSpaceStandard(self.treeData)
      },
      // 级联选择 提取树 根节点
      treeRoot: function (arr) {
        let self = this
        let len = arr.length
        for (let i = 0; i < len; i++) {
          if (arr[i].parentId === 0) {
            arr[i].children = []
            return self.treeNode(arr, arr[i])
          }
        }
      },
      // 级联选择 提取树 子节点
      treeNode: function (arr, one) {
        let self = this
        let len = arr.length
        one.children = []
        for (let i = 0; i < len; i++) {
          if (one.id === arr[i].parentId) {
            arr[i].children = []
            one.children.push(self.treeNode(arr, arr[i]))
          }
        }
        return one
      },
      // 选中时
      treeHandleSelect: function (selectedList) {
        let self = this
        if (selectedList.length > 0) {
          self.iotSpace = selectedList
          let ele = selectedList[selectedList.length - 1] // 当前选中的树节点
          if (ele.expand) {
            ele.expand = false
          } else {
            ele.expand = true
          }
        }
      },
      // 空间初始化
      spaceInit: function (obj, arr) {
        let self = this
        let len = arr.length
        for (let i = 0; i < len; i++) {
          if (obj.id === arr[i].id) {
            arr[i].selected = true
            return
          } else {
            if (arr[i].children.length > 0) {
              self.spaceInit(obj, arr[i].children)
            }
          }
          if (i === (len - 1)) {
            return
          }
        }
      },
      // 设备控件级联菜单数据 标准化处理
      deviceSpaceStandard: function (arr) {
        let self = this
        let len = arr.length
        let temArr = []
        for (let i = 0; i < len; i++) {
          let one = {
            value: arr[i].id,
            label: arr[i].name,
            children: self.deviceSpaceStandard(arr[i].children)
          }
          temArr.push(one)
        }
        return temArr
      },
      // 级联菜单变化
      cascaderChange: function (value) {
        let self = this
        if (value.length > 0) {
          let lastIndex = value.length - 1
          let id = value[lastIndex]
          let obj = this.id2name(self.treeDataTem, id)
          self.formValidate.iotSpace = obj
        }
      },
      // 获取级联id对应的name
      id2name: function (arr, id) {
        let len = arr.length
        for (let i = 0; i < len; i++) {
          if (id === arr[i].id) {
            return arr[i]
          }
        }
      },
      // 自定义 级联菜单显示
      cascaderFormat: function (labels, selectedData) {
        let self = this
        let index = labels.length - 1
        if (selectedData.length > 0) {
          if (self.updateInit) {
            // 弹框初始化后，会走到这一步，引起旧数据对传过来的值替换
            self.updateInit = false
            self.deviceSpaceText = labels[0]
          } else {
            let id = selectedData[index].value
            let obj = self.id2name(self.treeDataTem, id)
            self.formValidate.iotSpace = obj
            self.deviceSpaceText = labels.join('>')
            // self.deviceSpaceText = selectedData[index].label
          }
        }
        // return labels[index]
        return self.deviceSpaceText
      },
      // 设备类型list
      devTypeList: function () {
        let self = this
        let getData = {
          'size': 100,
          'page': 0
        }
        window.myapi.devType_list(getData).then(function (res) {
          self.deviceTypeList = []
          if (res.data.status === 200) {
            self.deviceTypeList = res.data.data.content
          } else {
            let msg = res.data.msg ? res.data.msg : '请求数据失败!'
            self.$Message.error({content: msg, duration: 5, closable: true})
          }
        }).catch(function (e) {
          if (e && e.response && e.response.data) {
            let msg = e.response.data.message ? e.response.data.message : '请求数据失败!'
            self.$Message.error({content: msg, duration: 0, closable: true})
          }
        })
      },
      // 记录 设备类型选择单击
      optionClick: function (item) {
        if (!(item === undefined || item.id === undefined)) {
          this.devTypeObj = JSON.parse(JSON.stringify(item))
          window.vm.$emit('deviceTypeObj', this.devTypeObj)
        }
      },
      spaceInputChange: function (data) {
      }
    }
  }

</script>
